package com.hifar.demo3;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import com.hifar.demo3.model.DmData;
import com.hifar.demo3.model.DmTable;
import com.hifar.demo3.model.PreliminaryRequirements;
import com.hifar.demo3.model.ProcedureStep;
import com.hifar.demo3.pojo.SupportEquipment;
import com.hifar.demo3.pojo.TableCell;
import com.hifar.demo3.pojo.TableRow;

import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

public class WordReportGenerator {
    public void generateReport(DmData dmData, String outputPath) throws Exception {
        // 1. 创建新文档
        XWPFDocument document = new XWPFDocument();
        
        // 2. 添加文档标题
        addTitle(document, dmData.getDmIdent().getTechName());
        
        // 3. 添加基本信息
        addBasicInfo(document, dmData);
        
        // 4. 添加前提要求
        addPreliminaryRequirements(document, dmData.getPreliminaryRequirements());
        
        // 5. 添加主程序步骤
        addProcedureSteps(document, dmData.getMainProcedureSteps());
        
        // 6. 添加表格数据
        addTables(document, dmData.getTables());
        
        // 7. 添加检验结论
        addConclusion(document, dmData.getMainProcedureSteps());
        
        // 8. 保存文档
        try (FileOutputStream out = new FileOutputStream(outputPath)) {
            document.write(out);
        }
        
        document.close();
    }
    
    private void addTitle(XWPFDocument document, String title) {
        XWPFParagraph titlePara = document.createParagraph();
        titlePara.setAlignment(ParagraphAlignment.CENTER);
        
        XWPFRun titleRun = titlePara.createRun();
        titleRun.setText(title);
        titleRun.setBold(true);
        titleRun.setFontSize(18);
        titleRun.setFontFamily("宋体");
        titleRun.addBreak();
    }
    
    private void addBasicInfo(XWPFDocument document, DmData dmData) {
        XWPFParagraph para = document.createParagraph();
        para.setAlignment(ParagraphAlignment.LEFT);
        
        XWPFRun run = para.createRun();
        run.setText("文档编号: " + buildDmCodeString(dmData.getDmIdent().getDmCode()));
        run.addBreak();
        run.setText("版本号: " + dmData.getDmIdent().getIssueNumber());
        run.addBreak();
        run.setText("发布日期: " + dmData.getDmIdent().getIssueDate());
        run.addBreak();
        run.setText("安全等级: " + dmData.getDmStatus().getSecurityClassification());
        run.addBreak();
        run.addBreak();
    }
    
    private String buildDmCodeString(Map<String, String> dmCode) {
        return String.format("%s-%s-%s-%s-%s-%s-%s-%s-%s-%s-%s",
            dmCode.get("modelIdentCode"),
            dmCode.get("systemDiffCode"),
            dmCode.get("systemCode"),
            dmCode.get("subSystemCode"),
            dmCode.get("subSubSystemCode"),
            dmCode.get("assyCode"),
            dmCode.get("disassyCode"),
            dmCode.get("disassyCodeVariant"),
            dmCode.get("infoCode"),
            dmCode.get("infoCodeVariant"),
            dmCode.get("itemLocationCode"));
    }
    
    private void addPreliminaryRequirements(XWPFDocument document, PreliminaryRequirements requirements) {
        XWPFParagraph titlePara = document.createParagraph();
        titlePara.setAlignment(ParagraphAlignment.LEFT);
        
        XWPFRun titleRun = titlePara.createRun();
        titleRun.setText("前提要求");
        titleRun.setBold(true);
        titleRun.setFontSize(14);
        titleRun.addBreak();
        
        // 添加条件
        if (requirements.getConditions() != null && !requirements.getConditions().isEmpty()) {
            XWPFParagraph condPara = document.createParagraph();
            XWPFRun condRun = condPara.createRun();
            condRun.setText("条件:");
            condRun.setBold(true);
            
            for (String condition : requirements.getConditions()) {
                XWPFParagraph itemPara = document.createParagraph();
                itemPara.setIndentationLeft(400);
                XWPFRun itemRun = itemPara.createRun();
                itemRun.setText("• " + condition);
            }
        }
        
        // 添加支持设备
        if (requirements.getSupportEquipments() != null && !requirements.getSupportEquipments().isEmpty()) {
            XWPFParagraph equipPara = document.createParagraph();
            XWPFRun equipRun = equipPara.createRun();
            equipRun.setText("支持设备:");
            equipRun.setBold(true);
            
            // 创建表格
            XWPFTable table = document.createTable(requirements.getSupportEquipments().size() + 1, 4);
            
            // 设置表格宽度
            table.setWidth("100%");
            
            // 添加表头
            XWPFTableRow headerRow = table.getRow(0);
            headerRow.getCell(0).setText("代码");
            headerRow.getCell(1).setText("名称");
            headerRow.getCell(2).setText("类型");
            headerRow.getCell(3).setText("数量");
            
            // 添加数据行
            for (int i = 0; i < requirements.getSupportEquipments().size(); i++) {
                SupportEquipment equip = requirements.getSupportEquipments().get(i);
                XWPFTableRow row = table.getRow(i + 1);
                row.getCell(0).setText(equip.getCode());
                row.getCell(1).setText(equip.getName());
                row.getCell(2).setText(equip.getType());
                row.getCell(3).setText(equip.getQuantity());
            }
        }
        
        document.createParagraph().createRun().addBreak();
    }
    
    private void addProcedureSteps(XWPFDocument document, List<ProcedureStep> steps) {
        if (steps == null || steps.isEmpty()) return;
        
        XWPFParagraph titlePara = document.createParagraph();
        titlePara.setAlignment(ParagraphAlignment.LEFT);
        
        XWPFRun titleRun = titlePara.createRun();
        titleRun.setText("检查步骤");
        titleRun.setBold(true);
        titleRun.setFontSize(14);
        titleRun.addBreak();
        
        for (ProcedureStep step : steps) {
            addProcedureStep(document, step, 0);
        }
    }
    
    private void addProcedureStep(XWPFDocument document, ProcedureStep step, int level) {
        // 创建步骤标题段落
        XWPFParagraph stepPara = document.createParagraph();
        stepPara.setAlignment(ParagraphAlignment.LEFT);
        stepPara.setIndentationLeft(level * 400); // 根据层级缩进
        
        XWPFRun stepRun = stepPara.createRun();
        stepRun.setText(step.getTitle());
        stepRun.setBold(level < 2); // 前两级加粗
        
        // 添加步骤描述
        if (step.getDescription() != null && !step.getDescription().isEmpty()) {
            XWPFParagraph descPara = document.createParagraph();
            descPara.setIndentationLeft((level + 1) * 400);
            XWPFRun descRun = descPara.createRun();
            descRun.setText(step.getDescription());
        }
        
        // 添加操作数据
        if (!step.getOperationData().isEmpty()) {
            XWPFParagraph dataPara = document.createParagraph();
            dataPara.setIndentationLeft((level + 1) * 400);
            XWPFRun dataRun = dataPara.createRun();
            dataRun.setText("操作数据:");
            dataRun.setItalic(true);
            
            for (Map.Entry<String, String> entry : step.getOperationData().entrySet()) {
                XWPFParagraph itemPara = document.createParagraph();
                itemPara.setIndentationLeft((level + 2) * 400);
                XWPFRun itemRun = itemPara.createRun();
                itemRun.setText("• " + entry.getKey() + ": " + entry.getValue());
            }
        }
        
        // 递归添加子步骤
        if (step.getSubSteps() != null) {
            for (ProcedureStep subStep : step.getSubSteps()) {
                addProcedureStep(document, subStep, level + 1);
            }
        }
    }
    
    private void addTables(XWPFDocument document, List<DmTable> tables) {
        if (tables == null || tables.isEmpty()) return;
        
        XWPFParagraph titlePara = document.createParagraph();
        titlePara.setAlignment(ParagraphAlignment.LEFT);
        
        XWPFRun titleRun = titlePara.createRun();
        titleRun.setText("检查数据记录");
        titleRun.setBold(true);
        titleRun.setFontSize(14);
        titleRun.addBreak();
        
        for (DmTable table : tables) {
            // 添加表格标题
            XWPFParagraph tableTitlePara = document.createParagraph();
            XWPFRun tableTitleRun = tableTitlePara.createRun();
            tableTitleRun.setText(table.getTitle());
            tableTitleRun.setBold(true);
            tableTitleRun.addBreak();
            
            // 创建Word表格
            XWPFTable wordTable = document.createTable(table.getRows().size(), 
                table.getRows().get(0).getCells().size());
            wordTable.setWidth("100%");
            
            // 填充表格数据
            for (int i = 0; i < table.getRows().size(); i++) {
                TableRow row = table.getRows().get(i);
                XWPFTableRow wordRow = wordTable.getRow(i);
                
                for (int j = 0; j < row.getCells().size(); j++) {
                    TableCell cell = row.getCells().get(j);
                    XWPFTableCell wordCell = wordRow.getCell(j);
                    
                    // 处理合并单元格
                    if (cell.getColspan() > 1 || cell.getRowspan() > 1) {
                        // 设置水平合并
                        if (cell.getColspan() > 1) {
                            // 设置起始单元格
                            wordCell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                            
                            // 设置被合并的单元格
                            for (int k = 1; k < cell.getColspan(); k++) {
                                if (j + k < wordRow.getTableCells().size()) {
                                    XWPFTableCell mergedCell = wordRow.getCell(j + k);
                                    mergedCell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                                }
                            }
                        }
                        
                        // 设置垂直合并
                        if (cell.getRowspan() > 1) {
                            // 设置起始单元格
                            wordCell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                            
                            // 设置被合并的单元格
                            for (int k = 1; k < cell.getRowspan(); k++) {
                                if (i + k < wordTable.getRows().size()) {
                                    XWPFTableRow mergedRow = wordTable.getRow(i + k);
                                    if (j < mergedRow.getTableCells().size()) {
                                        XWPFTableCell mergedCell = mergedRow.getCell(j);
                                        mergedCell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                                    }
                                }
                            }
                        }
                        
                        // 设置单元格宽度
                        if (cell.getColspan() > 1) {
                            wordCell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1000 * cell.getColspan()));
                        }
                    }
                    
                    // 设置单元格内容
                    wordCell.setText(cell.getContent() != null ? cell.getContent() : "");
                }
            }
            
            document.createParagraph().createRun().addBreak();
        }
    }
    
    private void addConclusion(XWPFDocument document, List<ProcedureStep> steps) {
        if (steps == null || steps.isEmpty()) return;
        
        // 查找检验结论步骤
        for (ProcedureStep step : steps) {
            if ("检验结论".equals(step.getTitle())) {
                XWPFParagraph titlePara = document.createParagraph();
                titlePara.setAlignment(ParagraphAlignment.LEFT);
                
                XWPFRun titleRun = titlePara.createRun();
                titleRun.setText("检验结论");
                titleRun.setBold(true);
                titleRun.setFontSize(14);
                titleRun.addBreak();
                
                // 添加结论内容
                XWPFParagraph conclPara = document.createParagraph();
                XWPFRun conclRun = conclPara.createRun();
                
                String conclusion = step.getOperationData().values().iterator().next();
                conclRun.setText("结论: " + conclusion);
                conclRun.setBold(true);
                conclRun.setColor(conclusion.contains("合格") ? "008000" : "FF0000");
                
                break;
            }
        }
    }
}